import xlsxwriter as xlsxwriter
from flask import Blueprint, request, make_response
import os
from flask import Blueprint
from xlrd import open_workbook

from io import BytesIO
from xlrd import open_workbook
from urllib.parse import quote
from db import Dd
import datetime
import mimetypes

views = Blueprint('views', __name__)


# 导入excel
@views.route('/upload', methods=['POST'])
def uploads():
    print(request.files)
    fileilename = request.files['file']
    print(request.files['file'])
    fileilename.save(os.path.join('./static/' + fileilename.filename))
    name = 'static/' + fileilename.filename
    bk = open_workbook(name, encoding_override='utf-8')
    sh = bk.sheets()[0]
    nrows = sh.nrows
    ncols = sh.ncols
    # 行
    for i in range(2, nrows):
        row_date = sh.row_values(i)
        for x in range(0, ncols):
            print(row_date[x])
    return 'ok'


@views.route('/download', methods=["GET", "POST"])
def download():
    # 实例化二进制数据
    out = BytesIO()
    # 创建一个Excel实例
    workbook = xlsxwriter.Workbook(out)
    # 添加一个sheet，add_worksheet()，默认"Sheet1"，可自定义命名，add_worksheet("资产列表")
    table = workbook.add_worksheet()
    # table.write(行, 列, 字段名)
    # 行、列从 0 开始计数
    # 字段命名根据每个人使用情况而定，插入数据部分也是
    table.write(0, 0, "资产编号")
    table.write(0, 1, "资产名称")

    workbook.close()
    filename = quote("资产列表_{}.xlsx".format(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))
    file = make_response(out.getvalue())
    out.close()
    mime_type = mimetypes.guess_type('%s.xlsx' % filename)[0]
    file.headers['Content-Type'] = mime_type
    file.headers["Cache-Control"] = "no-cache"
    file.headers['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(filename)
    return file


@views.route('/acporgn', methods=["GET"])
def acporgn():
    sql = "select * from `organ`"
    db = Dd()
    orgn = db.get_all(sql)
    if not orgn:
        return orgn
    #  先把列表重组成字典
    dict1 = {}
    list1 = []
    for i in orgn:
        dict1[i['id']] = i
    for j in orgn:
        level=j['level']
        #  pid等于0，就是顶级，
        if level == 0:
            # 直接加入列表
            list1.append(j)
        else:
        #     #  查看父类是否有子类
            if 'children' not in dict1[level]:
                dict1[level]['children'] = []
                dict1[level]['children'].append(j)
    print(list1)
    return {'code':'200','list1':list1}

# #  无限极分类数据重构展示
# def test_data(data):
#     if not data:
#         return data
#     #  先把列表重组成字典
#     dict1 = {}
#     list1 = []
#     for i in data:
#         dict1[i['id']] = i
#
#     for j in data:
#         pid = j['pid']
#         #  pid等于0，就是顶级，
#         if pid == 0:
#             # 直接加入列表
#             list1.append(j)
#         else:
#             #  查看父类是否有子类
#             if 'son' not in dict1[pid]:
#                 dict1[pid]['son'] = []
#             dict1[pid]['son'].append(j)
#     return list1
